var fileListApp;
var filePathInfo = {};
var tree;
var newfilepath = "";
$(document).ready(function () {

    var thisURL = document.URL;
    var urlSplit = decodeURI(thisURL).split('?');

    if (urlSplit.length == 1) {
        filePathInfo.filepath = "/";
    } else {
        var getval = urlSplit[1].split("&");
        if (getval.length == 1) {
            filePathInfo.filepath = "/";
        }

        //url参数转换为键值对
        for (var i = 0; i < getval.length; i++) {
            var fileinfokey = getval[i].split("=")[0];
            var fileinfovalue = getval[i].split("=")[1];
            filePathInfo[fileinfokey] = fileinfovalue;
        }
    }

    fileListApp = new Vue({
        el: '#fileListId',
        data: {
            fileList: [],
            breadCrumbList: []
        },
        created: function () {
            this.initFile();
            this.initBreadCrumb();
            showStorage();

        },

        methods: {
            selectFileByFileType: function(fileType){
                $.ajax({
                    data: {fileType:fileType},
                    url: "/file/selectFileByFileType",
                    dataType: "json",
                    type: "get",
                    async: true,
                    success: function (result) {
                        if (result.success) {
                            console.log(result.data);
                        }
                    },
                    error: function () {
                        //alert("系统繁忙!");
                    }
                });
            },

            initBreadCrumb: function () {
                var filepath = filePathInfo.filepath;
                var nameArr = filepath.split("/");

                var tempPath = "/";
                var breadCrumbList = [];
                var breadCrumbObj = {};
                breadCrumbObj.breadName = "全部文件";
                breadCrumbObj.breadPath = "/file/fileIndex.html?filepath=/";
                breadCrumbList.push(breadCrumbObj);
                for (var i = 0; i < nameArr.length; i++) {
                    if (nameArr[i] == "") {
                        continue;
                    }
                    tempPath += nameArr[i];
                    tempPath += "/"
                    //htmlStr += "<a href='/file/fileIndex.html?filepath=" +tempPath +"'>"+nameArr[i]+"</a>";
                    var breadCrumbObj = {};
                    breadCrumbObj.breadName = nameArr[i];
                    breadCrumbObj.breadPath = "/file/fileIndex.html?filepath=" + tempPath;
                    breadCrumbList.push(breadCrumbObj)

                }
                this.breadCrumbList = breadCrumbList;
                //$("#headcrumbid").html(htmlStr);
            },
            clickFileName: function (index, row) {
                window.location.href = row.url;
            },
            handleEdit: function (index, row) {
                console.log(index, row);
            },
            handleDelete: function (index, fileInfo) {
                $.ajax({
                    data: fileInfo,
                    url: "/file/deleteFile",
                    dataType: "json",
                    type: "POST",
                    async: true,
                    success: function (result) {
                        if (result.success) {
                            alert("删除成功");
                            fileListApp.initFile();
                        } else {
                            alert(result.errorMessage);
                        }
                    },
                    error: function () {
                        //alert("系统繁忙!");
                    }
                });
            },
            initFile: function () {
                var filepath = filePathInfo.filepath;
                if (filepath == null || filepath == "" || filepath == "/") {
                    filepath = "/";
                }

                getFileList(filepath)
            },
            moveFile: function (file) {
                var oldfilepath = file.filepath;
                var filename = file.filename;
                layer.open({
                    title: "选择目录",
                    type: 2,
                    area: ['700px', '450px'],
                    fixed: false, //不固定
                    maxmin: true,
                    btn: ['确定', '取消'],
                    content: "filetree.html",
                    yes: function (index, layero) {
                        console.log(oldfilepath);
                        console.log(newfilepath);
                        var fileInfo = {
                            oldfilepath: oldfilepath,
                            newfilepath: newfilepath,
                            filename: filename
                        };
                        $.ajax({
                            data: fileInfo,
                            url: "/file/moveFile",
                            dataType: "json",
                            type: "POST",
                            async: true,
                            success: function (result) {
                                if (result.success) {
                                    alert("移动成功");
                                    fileListApp.initFile();
                                } else {
                                    alert(result.errorMessage);
                                }
                            },
                            error: function () {
                                //alert("系统繁忙!");
                            }
                        });
                        // var iframeWin = window[layero.find('iframe')[0].name];
                        // iframeWin.saveEditAlbumInfo(indexAlbum);
                    },
                    btn2: function (index, layero) {
                        layer.close(index);
                    },
                    cancel: function () {
                        //右上角关闭回调

                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                });
            },
            showFile: function (file) {
                layer.open({
                    type: 2,
                    title: false,
                    area: ['630px', '360px'],
                    shade: 0.8,
                    closeBtn: 0,
                    shadeClose: true,
                    content: file.fileurl
                });
            },
            downloadFile: function (file) {
                var url = "/filetransfer/downloadFile";

                var form = $("<form></form>").attr("action", url).attr("method", "post");
                form.append($("<input></input>").attr("type", "hidden").attr("name", "filename").attr("value", file.filename));
                form.append($("<input></input>").attr("type", "hidden").attr("name", "fileurl").attr("value", file.fileurl));
                form.append($("<input></input>").attr("type", "hidden").attr("name", "extendname").attr("value", file.extendname));
                form.appendTo('body').submit().remove();
            },
            deleteFile: function (file) {

            },
            unzipFile: function (fileInfo) {
                $.ajax({
                    data: fileInfo,
                    url: "/file/unzipFile",
                    dataType: "json",
                    type: "POST",
                    async: true,
                    success: function (result) {
                        if (result.success) {
                            alert("解压成功");
                            fileListApp.initFile();
                        } else {
                            alert(result.errorMessage);
                        }
                    },
                    error: function () {
                        //alert("系统繁忙!");
                    }
                });
            }

        }
    });


    layui.use('upload', function () {
        var upload = layui.upload;

        //多文件列表示例
        var demoListView = $('#demoList')
            , uploadListIns = upload.render({
            elem: '#uploadFileId'
            , url: '/filetransfer/uploadFile/'
            , data: {
                filepath: filePathInfo.filepath,
                isDir: 0
            }
            , accept: 'file'
            , multiple: true
            , done: function (res, index, upload) {
                if (res.success) { //上传成功
                    alert("上传成功");

                }
            }

        });


    });

});


function back() {
    if (filePathInfo.filepath == "/") {
        return;
    }
    var thisURL = document.URL;
    var arr = thisURL.split("/");
    var name = arr[arr.length - 1];
    if (name == "") {
        name = arr[arr.length - 2];
    }
    window.location.href = thisURL.replace(name + "/", "")
}

function getFileList(filepath) {
    $.ajax({
        url: "/file/getFileList",
        data: {
            filepath: filepath,
        },
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {

                var data = result.data;

                var dirArr = [];
                var fileArr = [];
                for (var i = 0; i < data.length; i++) {
                    var isdir = data[i].isdir;
                    var filename = data[i].filename;
                    var extendname = data[i].extendname;

                    var url = "/file/fileIndex.html?filepath=" + filePathInfo.filepath + filename + "/";
                    fileurl = data[i].fileurl;
                    imageurl = "image/dir.png";

                    if (isdir == 0) {
                        url = fileurl;
                        imageurl = getFileName(extendname);

                    }
                    var dataMap = data[i];
                    dataMap.isdir= isdir;
                    dataMap.isshow = false;

                    dataMap.imageurl =  imageurl;
                    dataMap.extendname= extendname;
                    dataMap.url = url;


                    if (isdir == 1) {
                        dirArr.push(dataMap);
                    } else {
                        fileArr.push(dataMap);
                    }
                }
                fileListApp.fileList = dirArr.concat(fileArr);

            } else {
                alert("失敗" + result);
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });
}

function getFileName(extendname) {
    if (extendname == "png" || extendname == "jpg" || extendname == "jpeg") {
        extendname = "pic";
    } else if (extendname == "docx" || extendname == "doc") {
        extendname = "word";
    } else if (extendname == "ppt" || extendname == "pptx") {
        extendname = "ppt";
    } else if (extendname == "xls" || extendname == "xlsx") {
        extendname = "excel";
    } else if (extendname == "mp4") {
        extendname = "video";
    }
    var imageUrl = "image/file_" + extendname + ".png";
    return imageUrl;

}


function addFolderWindow() {
    layer.prompt({title: '添加文件夹', formType: 3}, function (text, index) {
        layer.close(index);
        createFile(text);
    });
}

function createFile(fileName) {
    $.ajax({
        data: {
            filename: fileName,
            filepath: filePathInfo.filepath,
            isdir: 1
        },
        url: "/file/createFile",
        dataType: "json",
        type: "POST",
        success: function (result) {
            alert("创建文件夹成功")
            fileListApp.initFile();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}

function showStorage() {
    $.ajax({
        url: "/filetransfer/getStorage",
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {
                $("#storageid").text((result.data.storagesize / (1024 * 1024)).toFixed(2));
            } else {
                alert("失敗" + result);
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });
}
